/*
 * JAVE - A Java Audio/Video Encoder (based on FFMPEG)
 *
 * Copyright (C) 2008-2009 Carlo Pelliccia (www.sauronsoftware.it)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cn.onlov.video.util.encoder;

import cn.onlov.video.bus.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.*;

/**
 * The default ffmpeg executable locator, which exports on disk the ffmpeg
 * executable bundled with the library distributions. It should work both for
 * windows and many linux distributions. If it doesn't, try compiling your own
 * ffmpeg executable and plug it in JAVE with a custom {@link FFMPEGLocator}.
 *
 * @author Carlo Pelliccia
 */
@Slf4j
public class DefaultFFMPEGLocator extends FFMPEGLocator {

    /**
     * Trace the version of the bundled ffmpeg executable. It's a counter: every
     * time the bundled ffmpeg change it is incremented by 1.
     */
    private static final int myEXEversion = 1;

    /**
     * The ffmpeg executable file path.
     */
    private String path;

    /**
     * It builds the default FFMPEGLocator, exporting the ffmpeg executable on a
     * temp file.
     */
    public DefaultFFMPEGLocator() {

        boolean isWindows;
        String os = System.getProperty("os.name").toLowerCase();
        if (os.indexOf("windows") != -1) {
            isWindows = true;
        } else {
            isWindows = false;
        }
        if (null == path) {
            if (isWindows) {
                String windowsFfmpeg = SystemUtil.getWindowsFfmpeg();
                path = windowsFfmpeg;
            } else {
                String linuxFfmpeg = SystemUtil.getLinuxFfmpeg();
                path = linuxFfmpeg;
            }
        }

        /**
         * 原有查找项目中的ffmpeg.exe
         */
        // Temp dir?
//		File temp = new File(System.getProperty("java.io.tmpdir"), "jave-"
//				+ myEXEversion);
//		if (!temp.exists()) {
//			temp.mkdirs();
//			temp.deleteOnExit();
//		}
//		log.info("temp路径：-----------------"+temp.getAbsolutePath());
//		// ffmpeg executable export on disk.
//		String suffix = isWindows ? ".exe" : "";
//		File exe = new File(temp, "ffmpeg" + suffix);
//		if (!exe.exists()) {
//			try {
////				InputStream is = this.getClass().getResourceAsStream("/config.json");
////				BufferedReader br = new BufferedReader(new InputStreamReader(is));
////				String s="";
////				String configContentStr = "";
////				try {
////					while((s=br.readLine())!=null) {
////						configContentStr = configContentStr+s;
////					}
////				} catch (IOException e) {
////
////					e.printStackTrace();
////				}
//
////				File file = ResourceUtils.getFile("ffmpeg/"+"ffmpeg" + suffix);
//				String fpath = null;
//
//				if(isWindows){
//					File file = ResourceUtils.getFile("classpath:ffmpeg/ffmpeg"+suffix);
//					fpath = file.getAbsolutePath();
//				}else{
//					fpath = "../../../ffmpeg/ffmpeg"+suffix;
//				}
//				log.info("ffmpeg路径：-------------"+fpath);
//				copyFile(fpath, exe);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//
//		}
//		// pthreadGC2.dll
//		if (isWindows) {
//			File dll = new File(temp, "pthreadGC2.dll");
//			if (!dll.exists()) {
//				try {
//					String fpath = null;
////					File file = ResourceUtils.getFile("classpath:ffmpeg/"+"pthreadGC2.dll");
////					String fpath = file.getAbsolutePath();
////					copyFile(fpath, dll);
//
//					File file = ResourceUtils.getFile("classpath:ffmpeg/"+"pthreadGC2.dll");
//					fpath = file.getAbsolutePath();
//					copyFile(fpath, dll);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//
//			}
//		}
//		// Need a chmod?
//		if (!isWindows) {
//			Runtime runtime = Runtime.getRuntime();
//			try {
//				runtime.exec(new String[] { "/bin/chmod", "755",
//						exe.getAbsolutePath() });
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
        // Ok.
//		this.path = exe.getAbsolutePath();
    }

    protected String getFFMPEGExecutablePath() {
        return path;
    }

    /**
     * Copies a file bundled in the package to the supplied destination.
     *
     * @param path The name of the bundled file.
     * @param dest The destination.
     * @throws RuntimeException If aun unexpected error occurs.
     */
    private void copyFile(String path, File dest) throws RuntimeException {
        InputStream input = null;
        OutputStream output = null;
        try {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.indexOf("windows") != -1) {
                input = new FileInputStream(path);
            } else {
                input = this.getClass().getResourceAsStream(path);
            }

            output = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int l;
            while ((l = input.read(buffer)) != -1) {
                output.write(buffer, 0, l);
            }
        } catch (IOException e) {
            throw new RuntimeException("Cannot write file "
                    + dest.getAbsolutePath());
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (Throwable t) {
                    ;
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (Throwable t) {
                    ;
                }
            }
        }
    }

}
